package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.TDeptGroupMapper;
import com.ysd.lis.mapper.TUserGroupMapper;
import com.ysd.lis.mapper.pub.PubEmployeeMapper;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.*;
import com.ysd.lis.service.*;
import com.ysd.lis.vo.*;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2021-10-08
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserDeptMapper sysUserDeptMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysOrganizationService sysOrganizationService;
    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;
    @Autowired
    SysOrgDepartmentService sysOrgDepartmentService;
    @Autowired
    SysUserDeptService sysUserDeptService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    TDeptGroupMapper tDeptGroupMapper;
    @Autowired
    TUserGroupMapper tUserGroupMapper;

    @Autowired
    TUserGroupService tUserGroupService;
    @Autowired
    SysUserSignMapper sysUserSignMapper;
    @Autowired
    SysRoleDetailsMapper sysRoleDetailsMapper;
    @Autowired
    private SysModuleMapper sysModuleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysPointsMapper sysPointsMapper;
    @Autowired
    private SysUserAuthdetailMapper sysUserAuthdetailMapper;
    @Autowired
    private SysUserAuthdetailServiceImpl sysUserAuthdetailService;
    @Autowired
    private PubEmployeeServiceImpl pubEmployeeService;

    @Autowired
    private PubEmployeeMapper pubEmployeeMapper;

    @Autowired
    SysUserAuthdifferMapper sysUserAuthdifferMapper;

    @Autowired
    SysUserAuthdifferService sysUserAuthdifferService;

    @Autowired
    SysUserInstrSetupMapper sysUserInstrSetupMapper;

    @Autowired
    SysUserInstrSetupService SysUserInstrSetupService;

    @Autowired
    SysUserRptGroupMapper sysUserRptGroupMapper;
    @Autowired
    SysUserRptGroupService sysUserRptGroupService;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;


    public Result getlist(userPageParam userPageParam) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        Page<Map> page = new Page<Map>();
        page.setCurrent(userPageParam.getPageIndex());
        page.setSize(userPageParam.getPageSize());
        if (StringUtils.isNotBlank(userPageParam.getUsername())) {
            queryWrapper.like("a.username", userPageParam.getUsername());
        }
        if (StringUtils.isNotBlank(userPageParam.getOrgId())) {
            queryWrapper.eq("a.org_id", userPageParam.getOrgId());
        }
        queryWrapper.eq("a.del_flag", 0);
        Page<Map> customerPortraitPage = sysUserMapper.getUserList(page, queryWrapper);
        List<Map> records = customerPortraitPage.getRecords();
        records.forEach(a -> {
            Map<String, Object> orgMap = new HashMap<>();
            orgMap.put("id", a.get("did"));
            orgMap.put("name", a.get("orgname"));
            a.put("Organization", orgMap);
            List<Map> userRoles = new ArrayList<>();
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("roleId", a.get("rid"));
            userMap.put("userId", a.get("id"));
            Map<String, Object> role = new HashMap<>();
            role.put("id", a.get("rid"));
            role.put("roleName", a.get("rolename"));
            userMap.put("Role", role);
            userRoles.add(userMap);
            a.put("UserRoles", userRoles);
            List<Map> userDept = new ArrayList<>();

            List<TUserDeptList> dept = sysUserMapper.getUserDepartment(a.get("id").toString());
            dept.forEach(b -> {
                Map<String, Object> userDeptMap = new HashMap();
                userDeptMap.put("deptId", b.getId());
                userDeptMap.put("userId", b.getUserId());
                Map<String, Object> Depatment = new HashMap<>();
                Depatment.put("id", b.getId());
                Depatment.put("name", b.getName());
                userDeptMap.put("Department", Depatment);
                userDept.add(userDeptMap);
            });
            a.put("UserDepts", userDept);
        });
        Map returnMap = new HashMap();
        returnMap.put("list", records);
        returnMap.put("count", customerPortraitPage.getTotal());
        return Result.succ(1, "获取数据成功", returnMap);
    }

    @Override
    public Result findAllUserListByOrgDept(userPageParam userPageParam) {
        String orgDeptId = userPageParam.getOrgDeptId();
        //1.机构 2.部门
        String orgDeptType = userPageParam.getOrgDeptType();
        Page<SysUserVo> page = new Page<>();
        page.setCurrent(userPageParam.getPageIndex());
        page.setSize(userPageParam.getPageSize());
        if (orgDeptType.equals("1")) {
            //查询此机构及机构下的所有子机构
            List<SysOrganization> orgList = sysOrganizationMapper.getOrgByPid(orgDeptId);
            List<String> orgIds = orgList.stream().map(SysOrganization::getId).collect(Collectors.toList());
            userPageParam.setOrgIds(orgIds);
        } else if (orgDeptType.equals("2")) {
            //查询此部门及部门下所有的子部门
            List<SysOrgDepartment> deptList = sysOrgDepartmentMapper.getDeptByPid(orgDeptId);
            List<String> deptIds = deptList.stream().map(SysOrgDepartment::getId).collect(Collectors.toList());
            userPageParam.setDeptIds(deptIds);
        }
        Page<SysUserVo> userVoPage = sysUserMapper.getUserPageList(page, userPageParam);
        List<SysUserVo> userVoList = userVoPage.getRecords();

        if (userVoList.size() > 0) {
            List<String> userIds = userVoList.stream().map(SysUserVo::getId).collect(Collectors.toList());
            //签名
            LambdaQueryWrapper<SysUserSign> qryWrapper = new LambdaQueryWrapper<>();
            qryWrapper.in(SysUserSign::getUserId, userIds).orderByDesc(SysUserSign::getCreateTime);
            List<SysUserSign> sysUserSigns = sysUserSignMapper.selectList(qryWrapper);
            userVoList.forEach(a -> {
                Optional<SysUserSign> first = sysUserSigns.stream().filter(s -> s.getUserId().equals(a.getId())).findFirst();
                if (first.isPresent()) {
                    SysUserSign sysUserSign = first.get();
                    if (null != sysUserSign) {
                        a.setUserSign(sysUserSign.getServerUrl());
                    }
                }
            });
            //获取用户的角色
            RolePageParam rolePageParam = new RolePageParam();
            rolePageParam.setUserIds(userIds);
            List<SysUserRole> mapList = sysRoleMapper.getUsersRolesByUserIds(rolePageParam);
            for (SysUserRole role : mapList) {
                int indexOf = userIds.indexOf(role.getUserId());
                if (indexOf >= 0) {
                    SysUserVo sysUserVo = userVoList.get(indexOf);
                    List<SysUserRole> userRoleList = sysUserVo.getUserRoleList();
                    if (null == userRoleList) {
                        userRoleList = new ArrayList<>();
                        sysUserVo.setUserRoleList(userRoleList);
                    }
                    userRoleList.add(role);
                }
            }
            //获取用户的部门小组
            LambdaQueryWrapper<TUserGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(TUserGroup::getUserId, userIds).eq(TUserGroup::getDelFlag, '0');
            List<TUserGroup> userGroupList = tUserGroupMapper.selectList(lambdaQueryWrapper);
            for (TUserGroup group : userGroupList) {
                int index = userIds.indexOf(group.getUserId());
                if (index >= 0) {
                    SysUserVo sysUserVo = userVoList.get(index);
                    List<TUserGroup> groupList = sysUserVo.getUserGroupList();
                    if (null == groupList) {
                        groupList = new ArrayList<>();
                        sysUserVo.setUserGroupList(groupList);
                    }
                    groupList.add(group);
                }
            }
        }
        return Result.succ(1, "查询成功", userVoPage);
    }


    public Result getUserById(SysUser sysUser) {
        SysSingleUser sysSingleUser = sysUserMapper.getUserById(sysUser.getId());
        if (sysSingleUser != null && !"".equals(sysSingleUser.getId())) {
            List<TUserDeptList> userDepartment = sysUserMapper.getUserDepartment(sysSingleUser.getId());
            sysSingleUser.setOrg(userDepartment);
        }
        return Result.succ(1, "操作成功", sysSingleUser);
    }

    public Result removeUserById(SysUser sysUser) {
        sysUser.setDelFlag(1);
        return Result.succ(sysUserMapper.updateById(sysUser));
    }

    public Result getOrganization() {
        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        List<SysOrganization> sysOrganizations = sysOrganizationService.getBaseMapper().selectList(lambdaQueryWrapper);

        Map returnMap = new HashMap();
        returnMap.put("orgList", sysOrganizations);
        return Result.succ(1, "成功", returnMap);
    }

    public Result getRole() {
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRole::getDelFlag, 0);
        List<SysRole> sysRoles = sysRoleService.getBaseMapper().selectList(lambdaQueryWrapper);
        List<Map> returnList = new ArrayList();
        sysRoles.forEach(a -> {
            Map returnMap = new HashMap();
            returnMap.put("id", a.getId());
            returnMap.put("roleName", a.getRoleName());
            returnList.add(returnMap);
        });
        Map returnMap = new HashMap();
        returnMap.put("roleList", returnList);
        return Result.succ(1, "操作成功", returnMap);
    }

    public Result getOrgDepartment(OrgDepartmentParam orgDepartmentParam) {
        Map returnMap = new HashMap();
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        if (StringUtils.isNotBlank(orgDepartmentParam.getName())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getName());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getCode())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getCode, orgDepartmentParam.getCode());
        }
        if (null != orgDepartmentParam.getIsSample()) {
            lambdaQueryWrapper.eq(SysOrgDepartment::getIsSample, orgDepartmentParam.getIsSample());
        }
        if (null != orgDepartmentParam.getIsCheck()) {
            lambdaQueryWrapper.eq(SysOrgDepartment::getIsCheck, orgDepartmentParam.getIsCheck());
        }
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentService.getBaseMapper().selectList(lambdaQueryWrapper);
        sysOrgDepartments.forEach(a -> {
            LambdaQueryWrapper<TDeptGroup> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(TDeptGroup::getDelFlag, 0).eq(TDeptGroup::getDeptId, a.getId()).eq(TDeptGroup::getStatus, "1");
            List<TDeptGroup> tDeptGroups = tDeptGroupMapper.selectList(lambdaQueryWrapper1);
            a.setDeptGroupList(tDeptGroups);
        });
        returnMap.put("deptList", sysOrgDepartments);
        return Result.succ(1, "获取数据成功", returnMap);
    }

    public List<String> getUserRolePermissions(String userId) {
        return sysUserMapper.getUserRolePermissions(userId);
    }

    public SysUser getPassword(String username) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = this.baseMapper.selectOne(lambdaQueryWrapper);


        if (StringUtils.isNotBlank(sysUser.getHisEmployeeId())) {
            PubEmployee pubEmployee = pubEmployeeMapper.selectById(sysUser.getHisEmployeeId());
            if (Objects.nonNull(pubEmployee) && StringUtils.isNotBlank(pubEmployee.getCode())) {
                sysUser.setHisEmployeeCode(pubEmployee.getCode());
            }
        }


        Map data = (Map) sysOrganizationService.findOrgTree().getData();
        List<Map> orgTree = (List<Map>) data.get("orgTree");
        sysUser.setOrgList(orgTree);


        if (sysUser != null && sysUser.getOrgId() != null) {
            LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(SysOrganization::getDelFlag, 0).eq(SysOrganization::getId, sysUser.getOrgId());
            sysUser.setOrganization(sysOrganizationService.getBaseMapper().selectOne(lambdaQueryWrapper1));
            //获取此员工的部门ID
            LambdaQueryWrapper<SysUserDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserDept::getUserId, sysUser.getId()).eq(SysUserDept::getDelFlag, 0);
            SysUserDept userDept = sysUserDeptMapper.selectOne(queryWrapper);
            if (userDept != null) {
                SysOrgDepartment sysOrgDepartment = sysOrgDepartmentMapper.selectById(userDept.getDeptId());
                sysUser.setDeptId(userDept.getDeptId());
                if (sysOrgDepartment != null) {
                    sysUser.setDeptName(sysOrgDepartment.getName());
                }
            }
            //获取此员工默认进入的模块
            //获取此员工所有的模块
            // sysUser.setParentMenuList(sysUserMapper.findUserParentMenuList(sysUser.getId()));

            MPJLambdaWrapper<SysMenu> menuWrapper = new MPJLambdaWrapper<>();
            menuWrapper.selectAll(SysMenu.class).leftJoin(SysRoleMenu.class, SysRoleMenu::getMenuId, SysMenu::getId).leftJoin(SysRole.class, SysRole::getId, SysRoleMenu::getRoleId).leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getId).leftJoin(SysUser.class, SysUser::getId, SysUserRole::getUserId).eq(SysMenu::getDelFlag, '0').eq(SysUser::getId, sysUser.getId()).and(wrapper -> wrapper.eq(SysMenu::getParentId, "").or().isNull(SysMenu::getParentId)).orderByDesc(SysMenu::getCreateTime);
            List<SysMenu> sysMenus = sysMenuMapper.selectList(menuWrapper);
            sysUser.setParentMenuList(sysMenus);
        }
        return sysUser;
    }


    public Result findUserRoleMenuPermissionList(String userId) {
        MPJLambdaWrapper<SysRole> roleInfoByUserIdWrapper = new MPJLambdaWrapper<>();
        roleInfoByUserIdWrapper.selectAll(SysRole.class).leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getId).eq(SysUserRole::getUserId, userId);
        List<SysRole> sysRoles = sysRoleMapper.selectJoinList(SysRole.class, roleInfoByUserIdWrapper);
        if (sysRoles.size() == 0) {
            return Result.fail("该用户无角色信息");
        } else {
            // 构建返回集合
            Map<String, Object> resultMap = new HashMap<>();
            List<String> roleIds = sysRoles.stream().map(SysRole::getId).collect(Collectors.toList());
            // 获取模块列表
            MPJLambdaWrapper<SysModule> modelsByRoleIdsWrapper = new MPJLambdaWrapper<>();
            modelsByRoleIdsWrapper.distinct().selectAll(SysModule.class).leftJoin(SysRoleModule.class, SysRoleModule::getModuleId, SysModule::getId).eq(SysModule::getDelFlag, "0").in(SysRoleModule::getRoleId, roleIds);

            List<SysModule> sysModules = sysModuleMapper.selectList(modelsByRoleIdsWrapper);
            resultMap.put("modules", sysModules);

            // 获取模块与菜单对象
            MPJLambdaWrapper<SysMenu> menusByRoleIdsWrapper = new MPJLambdaWrapper<>();
            menusByRoleIdsWrapper.distinct().selectAll(SysMenu.class).leftJoin(SysRoleMenu.class, SysRoleMenu::getMenuId, SysMenu::getId).eq(SysMenu::getDelFlag, '0').in(SysRoleMenu::getRoleId, roleIds);
            List<SysMenu> sysMenus = sysMenuMapper.selectList(menusByRoleIdsWrapper);
            List<SysMenu> returnList = new ArrayList<>();
            sysMenus.stream().forEach(tMenu -> {
                if (StringUtils.isBlank(tMenu.getParentId())) {
                    tMenu.setChildren(getChildren(tMenu, sysMenus));
                    returnList.add(tMenu);
                }
            });

            Map<String, List<SysMenu>> moduleMenuMap = returnList.stream().collect(Collectors.groupingBy(SysMenu::getModuleId));
            resultMap.put("moduleMenuMap", moduleMenuMap);

            // 获取菜单功能点对象
            MPJLambdaWrapper<SysPoints> pointsListByRoleIdsWrapper = new MPJLambdaWrapper<>();
            pointsListByRoleIdsWrapper.distinct().selectAll(SysPoints.class).leftJoin(SysRolePoints.class, SysRolePoints::getPointsId, SysPoints::getId).eq(SysPoints::getDelFlag, "0").in(SysRolePoints::getRoleId, roleIds);
            List<SysPoints> sysPoints = sysPointsMapper.selectList(pointsListByRoleIdsWrapper);
            Map<String, List<SysPoints>> modulePointMap = sysPoints.stream().collect(Collectors.groupingBy(SysPoints::getModuleId));

            Map<String, List<String>> modulePointCodeMap = new HashMap<>();
            modulePointMap.forEach((key, value) -> {
                List<String> collect = value.stream().map(SysPoints::getCode).collect(Collectors.toList());
                modulePointCodeMap.put(key, collect);
            });
            resultMap.put("modulePointCodeMap", modulePointCodeMap);
            return Result.succ(1, "查询成功", resultMap);
        }
    }

    public List<SysMenu> getChildren(SysMenu a, List<SysMenu> menuList) {
        List<SysMenu> result = new ArrayList();
        for (SysMenu menu : menuList) {
            if (StringUtils.isBlank(menu.getParentId())) {
                menu.setParentName("");
            }
            if (StringUtils.isNotBlank(menu.getParentId()) && menu.getParentId().equals(a.getId())) {
                menu.setParentName(a.getTitle());
                result.add(menu);
            }
        }
        for (SysMenu menu : result) {
            menu.setChildren(getChildren(menu, menuList));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;
    }

    public Result findUserRoleMenuPermissionList(String userId, String defalMenuId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        List<UserRoleMenuPermissionEntity> userRoleMenuPermissionList = new ArrayList<>();
        if (sysUser != null && "0".equals(sysUser.getInitializeFlag())) {
            String ss = "[{\"icon\":\"\",\"mId\":\"1527199475453599746\",\"title\":\"用户初始化\",\"url\":\"\",\"id\":\"1520968635531571201\",\"order\":\"0\"},{\"icon\":\"icon-sysset\",\"mId\":\"1527200437299781634\",\"title\":\"用户初始化\",\"url\":\"\",\"parentId\":\"1527199475453599746\",\"id\":\"1520968635531571201\",\"order\":\"1\"},{\"icon\":\"icon-sysset\",\"mId\":\"1527201968006832130\",\"title\":\"用户基本信息\",\"url\":\"/labuserinfo\",\"parentId\":\"1527200437299781634\",\"id\":\"1520968635531571201\",\"order\":\"1\"}]\n";
            JSONArray objects = JSONUtil.parseArray(ss);
            userRoleMenuPermissionList = JSONUtil.toList(objects, UserRoleMenuPermissionEntity.class);
        } else {
            userRoleMenuPermissionList = sysUserMapper.findUserRoleMenuPermissionList(userId);
        }
        List<MenuTreeVo> menuTreeVoList = new ArrayList<>();
        RoleMenuPmsVo roleMenuPmsVo = new RoleMenuPmsVo();
        UserRoleMenuPermissionVo userRoleMenuPermissionVo = new UserRoleMenuPermissionVo();
        //映射成menuTreeVo实体
        userRoleMenuPermissionList.forEach(a -> {
            MenuTreeVo menuTreeVo = new MenuTreeVo();
            BeanUtil.copyProperties(a, menuTreeVo);
            menuTreeVo.setId(a.getMId());
            roleMenuPmsVo.setRoleId(a.getId());
            menuTreeVoList.add(menuTreeVo);
        });
        List<MenuTreeVo> MenuList = new ArrayList<MenuTreeVo>();
        //循环找所有一级菜单
        menuTreeVoList.forEach(a -> {
            if (StringUtils.isNotBlank(defalMenuId)) {
                if (defalMenuId.equals(a.getParentId())) {
                    a.setRootId(a.getId());
                    MenuList.add(a);
                }
            } else {
                if (StringUtils.isBlank(a.getParentId())) {
                    a.setRootId(a.getId());
                    MenuList.add(a);
                }
            }
        });
        MenuList.forEach(b -> {
            List<MenuTreeVo> child = getChild(b, menuTreeVoList);
            b.setChildren(child);
        });

        roleMenuPmsVo.setMenuTree(MenuList);
        //用户权限查询
        List<PermissionVo> permissionList = new ArrayList<>();
        List<TPermission> tPermissionList = sysUserMapper.findUserRolePermissionList(userId);
        //映射成menuTreeVo实体
        tPermissionList.forEach(a -> {
            PermissionVo permissionVo = new PermissionVo();
            BeanUtil.copyProperties(a, permissionVo);
            permissionList.add(permissionVo);
        });
        roleMenuPmsVo.setPermissionList(permissionList);

        //需核实几条
        List<RoleMenuPmsVo> roleMenuPmsVos = new ArrayList<>();
        roleMenuPmsVos.add(roleMenuPmsVo);

        userRoleMenuPermissionVo.setRoleMenuPmsList(roleMenuPmsVos);


        return Result.succ(1, "查询成功", userRoleMenuPermissionVo);
    }

    public List<MenuTreeVo> getChild(MenuTreeVo menuTreeVo, List<MenuTreeVo> menuTreeVoList) {
        List<MenuTreeVo> result = new ArrayList();
        for (MenuTreeVo menu : menuTreeVoList) {
            if (StringUtils.isNotBlank(menu.getParentId()) && menu.getParentId().equals(menuTreeVo.getId())) {
                menu.setRootId(menuTreeVo.getRootId());
                result.add(menu);
            }
        }
        for (MenuTreeVo menu : result) {
            menu.setChildren(getChild(menu, menuTreeVoList));
        }
        if (result.size() == 0) {
            return null;
        }
        return result;
    }

    @Override
    public Result addUserInfo(userAddParam user) {
        SysUser sysUser = new SysUser();
        String passwords = SecureUtil.md5("123456");//默认密码
        BeanUtil.copyProperties(user, sysUser);
        //sysUser.setOrgId("1518526677752029186");
        sysUser.setPassword(passwords);
        int insert = this.baseMapper.insert(sysUser);
        if (insert > 0) {
            //插入用户部门中间表
            if (StringUtils.isNotBlank(user.getDeptId())) {
                SysUserDept userDept = new SysUserDept();
                userDept.setUserId(sysUser.getId());
                userDept.setDeptId(user.getDeptId());
                sysUserDeptMapper.insert(userDept);
            }
            //插入用户角色中间表
            List<String> roleIds = user.getRoleIds();
            if (CollectionUtils.isNotEmpty(roleIds)) {
                List<SysUserRole> userRoleList = new ArrayList<>();
                roleIds.forEach(a -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRole.setRoleId(a);
                    userRoleList.add(sysUserRole);
                });
                sysUserRoleService.saveBatch(userRoleList);
            }
            // 插入用户权限详情表
//            sysUserAuthdetailService.addUserAfterDetails(sysUser, roleIds);
            return Result.succ(1, "保存成功", sysUser);
        } else {
            return Result.fail("保存失败");
        }
    }

    //新增用户
    public Result addUser(userAddParam user) {
        Map returnMap = new HashMap();
        SysUser sysUser = new SysUser();
        String passwords = SecureUtil.md5("Sgjk@2022");//默认密码
        BeanUtil.copyProperties(user, sysUser);
        sysUser.setPassword(passwords);
        //sysUser.setDelFlag(0);
        int insert = this.baseMapper.insert(sysUser);
        String id = sysUser.getId();

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(id);
        sysUserRole.setRoleId(user.getRoleId());
        //sysUserRole.setCreateTime(user.getCreateTime());
        //sysUserRole.setDelFlag(0);
        //sysUserRole.setCreator(user.getCreator());
        sysUserRoleService.getBaseMapper().insert(sysUserRole);

        List<String> deptIds = user.getDeptIds();
        if (CollectionUtils.isNotEmpty(deptIds)) {
            deptIds.forEach(a -> {
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(id);
                sysUserDept.setDeptId(a);
                sysUserDept.setDelFlag(0);
                sysUserDept.setCreator(user.getCreator());
                //sysUserDept.setCreateTime(user.getCreateTime());
                sysUserDeptService.getBaseMapper().insert(sysUserDept);
            });
        }
        if (insert > 0) {
            returnMap.put("roleId", user.getRoleId());
            returnMap.put("userId", id);
            return Result.succ(1, "注册成功", returnMap);
        } else {
            return Result.fail(400, "注册失败", insert);
        }
    }

    @Override
    public Result editUserInfo(userAddParam user) {
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(user, sysUser);
        int i = sysUserMapper.updateById(sysUser);
        if (i > 0) {
            //路径与修改用户信息冲突，只能通过username是否为空判断
            if (StringUtils.isNotBlank(user.getUsername())) {
                //删除用户部门中间表数据
                LambdaQueryWrapper<SysUserDept> delUserDeptWrapper = new LambdaQueryWrapper();
                delUserDeptWrapper.eq(SysUserDept::getUserId, user.getId());
                sysUserDeptMapper.delete(delUserDeptWrapper);
                //添加用户部门中间表
                if (StringUtils.isNotBlank(user.getDeptId())) {
                    SysUserDept userDept = new SysUserDept();
                    userDept.setUserId(user.getId());
                    userDept.setDeptId(user.getDeptId());
                    sysUserDeptMapper.insert(userDept);
                }
//
//                //删除用户部门小组中间表
//                LambdaQueryWrapper<TUserGroup> delUserGroupWrapper = new LambdaQueryWrapper<>();
//                delUserGroupWrapper.eq(TUserGroup::getUserId, user.getId());
//                tUserGroupMapper.delete(delUserGroupWrapper);
//                //插入用户部门小组中间表
//                List<String> groupIds = user.getGroupIds();
//                if (CollectionUtils.isNotEmpty(groupIds)) {
//                    List<TUserGroup> userGroupList = new ArrayList<>();
//                    groupIds.forEach(a -> {
//                        TUserGroup tUserGroup = new TUserGroup();
//                        tUserGroup.setUserId(user.getId());
//                        tUserGroup.setGroupId(a);
//                        userGroupList.add(tUserGroup);
//                    });
//                    tUserGroupService.saveBatch(userGroupList);
//                }

                //删除用户角色中间表
                LambdaQueryWrapper<SysUserRole> delUserRoleWrapper = new LambdaQueryWrapper<>();
                delUserRoleWrapper.eq(SysUserRole::getUserId, user.getId());
                sysUserRoleMapper.delete(delUserRoleWrapper);
                //插入用户角色中间表
                List<String> roleIds = user.getRoleIds();
                if (CollectionUtils.isNotEmpty(roleIds)) {
                    List<SysUserRole> userRoleList = new ArrayList<>();
                    roleIds.forEach(a -> {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(user.getId());
                        sysUserRole.setRoleId(a);
                        sysUserRole.setOrgId(user.getOrgId());
                        userRoleList.add(sysUserRole);
                    });
                    sysUserRoleService.saveBatch(userRoleList);
//                    // 先删除用户详情表数据
//                    LambdaUpdateWrapper<SysUserAuthdetail> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                    lambdaUpdateWrapper.set(SysUserAuthdetail::getDelFlag, "1").eq(SysUserAuthdetail::getUserId, sysUser.getId());
//                    int update = sysUserAuthdetailMapper.update(null, lambdaUpdateWrapper);
//                    // 插入用户权限详情表
//                    saveSysUserAuthdetail(sysUser.getId(), roleIds);
                }
            }
            return Result.succ(1, "保存成功", sysUser);
        } else {
            return Result.fail("保存失败");
        }
    }

    @Override
    public Result editUserInfo2(userAddParam user) {
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(user, sysUser);
        int i = sysUserMapper.updateById(sysUser);
        if (i > 0) {
            //路径与修改用户信息冲突，只能通过username是否为空判断
            if (StringUtils.isNotBlank(user.getUsername())) {
                //删除用户部门中间表数据
                LambdaQueryWrapper<SysUserDept> delUserDeptWrapper = new LambdaQueryWrapper();
                delUserDeptWrapper.eq(SysUserDept::getUserId, user.getId());
                sysUserDeptMapper.delete(delUserDeptWrapper);
                //添加用户部门中间表
                if (StringUtils.isNotBlank(user.getDeptId())) {
                    SysUserDept userDept = new SysUserDept();
                    userDept.setUserId(user.getId());
                    userDept.setDeptId(user.getDeptId());
                    sysUserDeptMapper.insert(userDept);
                }

                //删除用户部门小组中间表
                LambdaQueryWrapper<TUserGroup> delUserGroupWrapper = new LambdaQueryWrapper<>();
                delUserGroupWrapper.eq(TUserGroup::getUserId, user.getId());
                tUserGroupMapper.delete(delUserGroupWrapper);
                //插入用户部门小组中间表
                List<String> groupIds = user.getGroupIds();
                if (CollectionUtils.isNotEmpty(groupIds)) {
                    List<TUserGroup> userGroupList = new ArrayList<>();
                    groupIds.forEach(a -> {
                        TUserGroup tUserGroup = new TUserGroup();
                        tUserGroup.setUserId(user.getId());
                        tUserGroup.setGroupId(a);
                        userGroupList.add(tUserGroup);
                    });
                    tUserGroupService.saveBatch(userGroupList);
                }

                //删除用户角色中间表
                List<String> roleIds = user.getRoleIds();
                if (CollectionUtils.isNotEmpty(roleIds)) {
                    LambdaQueryWrapper<SysUserRole> delUserRoleWrapper = new LambdaQueryWrapper<>();
                    delUserRoleWrapper.eq(SysUserRole::getUserId, user.getId());
                    sysUserRoleMapper.delete(delUserRoleWrapper);
                    //插入用户角色中间表
                    if (CollectionUtils.isNotEmpty(roleIds)) {
                        List<SysUserRole> userRoleList = new ArrayList<>();
                        roleIds.forEach(a -> {
                            SysUserRole sysUserRole = new SysUserRole();
                            sysUserRole.setUserId(user.getId());
                            sysUserRole.setRoleId(a);
                            userRoleList.add(sysUserRole);
                        });
                        sysUserRoleService.saveBatch(userRoleList);
                    }
                }
            }
            return Result.succ(1, "保存成功", sysUser);
        } else {
            return Result.fail("保存失败");
        }
    }

    @Override
    public Result getUserPageList(userPageParam pageParam) {
        Page<SysUser> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysUser::getUsername, pageParam.getKeywords()).or().like(SysUser::getRealname, pageParam.getKeywords()));
        }
        Page<SysUser> userPage = sysUserMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", userPage);
    }

    //修改用户信息
    public Result eiditUser(userAddParam user) {
        Map returnMap = new HashMap();
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(user, sysUser);
        int i = sysUserMapper.updateById(sysUser);

        //路径与修改用户信息冲突，只能通过username是否为空判断
        if (StringUtils.isNotBlank(user.getUsername())) {

            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(user.getRoleId());
            int u = sysUserRoleService.getBaseMapper().update(sysUserRole, new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getId()));
            if (u == 0) {
                SysUserRole sysUserRole2 = new SysUserRole();
                sysUserRole2.setUserId(user.getId());
                sysUserRole2.setRoleId(user.getRoleId());
                sysUserRoleService.getBaseMapper().insert(sysUserRole2);
            }


            sysUserDeptService.getBaseMapper().delete(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, user.getId()));

            List<String> deptIds = user.getDeptIds();
            if (CollectionUtils.isNotEmpty(deptIds)) {
                deptIds.forEach(a -> {
                    SysUserDept sysUserDepts = new SysUserDept();
                    sysUserDepts.setUserId(user.getId());
                    sysUserDepts.setDeptId(a);
                    sysUserDepts.setDelFlag(0);
                    sysUserDepts.setEditor(user.getEditor());
                    sysUserDepts.setEditTime(user.getEditTime());
                    sysUserDeptService.getBaseMapper().insert(sysUserDepts);
                });
            }

            //设置人员分组
            //1.先删除人员下的分组关联数据
            LambdaQueryWrapper<TUserGroup> tUserGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tUserGroupLambdaQueryWrapper.eq(TUserGroup::getUserId, user.getId());
            tUserGroupMapper.delete(tUserGroupLambdaQueryWrapper);
            //2.将前台传来的ID循环入库
            List<String> groupIds = user.getGroupIds();
            if (CollectionUtils.isNotEmpty(groupIds)) {
                groupIds.forEach(a -> {
                    TUserGroup tUserGroup = new TUserGroup();
                    tUserGroup.setUserId(user.getId());
                    tUserGroup.setGroupId(a);
                    tUserGroupMapper.insert(tUserGroup);
                });
            }
        }
        returnMap.put("userId", user.getId());
        return Result.succ(1, "保存成功", returnMap);
    }

    //删除用户
    public Result userDeleteById(userDeleteParam userDelete) {
        Map returnMap = new HashMap();
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDelete, sysUser);
        sysUser.setDelFlag(1);
        this.baseMapper.updateById(sysUser);
        returnMap.put("userId", userDelete.getId());
        return Result.succ(1, "删除成功", returnMap);
    }

    @Override
    public Result deleteUserById(String id) {
        int deleteById = sysUserMapper.deleteById(id);
        if (deleteById > 0) {
            //删除用户部门表
            LambdaQueryWrapper<SysUserDept> delUserDeptWrapper = new LambdaQueryWrapper<>();
            delUserDeptWrapper.eq(SysUserDept::getUserId, id);
            sysUserDeptMapper.delete(delUserDeptWrapper);
            //删除用户分组表
            LambdaQueryWrapper<TUserGroup> delUserGroupWrapper = new LambdaQueryWrapper<>();
            delUserGroupWrapper.eq(TUserGroup::getUserId, id);
            tUserGroupMapper.delete(delUserGroupWrapper);
            //删除用户角色表
            LambdaQueryWrapper<SysUserRole> delUserRoleWrapper = new LambdaQueryWrapper<>();
            delUserRoleWrapper.eq(SysUserRole::getUserId, id);
            sysUserRoleMapper.delete(delUserRoleWrapper);
            // 删除用户详情表
            LambdaQueryWrapper<SysUserAuthdetail> delUserAuthWrapper = new LambdaQueryWrapper<>();
            delUserAuthWrapper.eq(SysUserAuthdetail::getUserId, id);
            sysUserAuthdetailMapper.delete(delUserAuthWrapper);
            Map returnMap = new HashMap();
            returnMap.put("userId", id);
            return Result.succ(1, "删除成功", returnMap);
        } else {
            return Result.fail("删除失败");
        }
    }

    public Result findUserSimple(String id) {
        Map returnsMap = new HashMap();
        Map returnMap = new HashMap();
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser != null) {
            returnMap.put("id", sysUser.getId());
            returnMap.put("hisNo", sysUser.getHisNo());
            returnMap.put("orgId", sysUser.getOrgId());
            returnMap.put("realname", sysUser.getRealname());
            returnMap.put("tel", sysUser.getTel());
            returnMap.put("username", sysUser.getUsername());
            returnMap.put("userMode", sysUser.getUserMode());
            returnMap.put("lisNo", sysUser.getLisNo());
            returnMap.put("email", sysUser.getEmail());
            returnMap.put("enable", sysUser.getEnable());
            returnMap.put("hisEmployeeId", sysUser.getHisEmployeeId());
            returnMap.put("hisEmployeeCode", sysUser.getHisEmployeeCode());
            returnMap.put("empowerNum", sysUser.getEmpowerNum());
            returnMap.put("inputCode", sysUser.getInputCode());
            returnMap.put("isTestDoctor", sysUser.getIsTestDoctor());
            returnMap.put("isChkDoctor", sysUser.getIsChkDoctor());
            returnMap.put("initializer",sysUser.getInitializer());
            MPJLambdaWrapper<SysUserDept> userDeptWrapper = new MPJLambdaWrapper<>();
            userDeptWrapper.select(SysUserDept::getDeptId).selectAs(SysOrgDepartment::getName, SysUserDept::getDeptName).leftJoin(SysOrgDepartment.class, SysOrgDepartment::getId, SysUserDept::getDeptId).eq(SysUserDept::getUserId, sysUser.getId()).eq(SysUserDept::getDelFlag, 0);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(userDeptWrapper);

            returnMap.put("depts", sysUserDepts);
            if (CollectionUtils.isNotEmpty(sysUserDepts)) {
                returnMap.put("deptId", sysUserDepts.get(0).getDeptId());
                returnMap.put("deptName", sysUserDepts.get(0).getDeptName());
            }
            //获取组织机构名称
            SysOrganization sysOrganization = sysOrganizationMapper.selectById(sysUser.getOrgId());
            if (sysOrganization != null) {
                returnMap.put("orgName", sysOrganizationMapper.selectById(sysUser.getOrgId()).getName());
            } else {
                returnMap.put("orgName", "");
            }

            MPJLambdaWrapper<SysUserRole> userRoleWrapper = new MPJLambdaWrapper<>();
            userRoleWrapper.select(SysUserRole::getRoleId).selectAs(SysRole::getRoleName, SysUserRole::getRoleName).leftJoin(SysRole.class, SysRole::getId, SysUserRole::getRoleId).eq(SysUserRole::getUserId, sysUser.getId()).eq(SysUserRole::getDelFlag, 0);
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(userRoleWrapper);


            returnMap.put("roles", sysUserRoles);
//            returnMap.put("groups",sysUserMapper.getUserGroup(sysUser.getId()));
            LambdaQueryWrapper<SysUserSign> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysUserSign::getUserId, id).orderByDesc(SysUserSign::getCreateTime);
            List<SysUserSign> sysUserSigns = sysUserSignMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(sysUserSigns)) {
                returnMap.put("userSign", sysUserSigns.get(0).getServerUrl());
            }
        }
        returnsMap.put("user", returnMap);
        return Result.succ(1, "成功", returnsMap);
    }

    public Result changePassword(changePasswordParam changePassword) {
        SysUser sysUser = sysUserMapper.selectById(changePassword.getId());
        if (changePassword.getChangeType() == 1){
            String oldPwd = SecureUtil.md5(changePassword.getOldPwd());
            if (!sysUser.getPassword().equals(oldPwd)) {
                return Result.fail(15, "旧密码错误", null);
            }
        }

        if (!changePassword.getNewPwd().equals(changePassword.getRepeatPwd())) {
            return Result.fail(400, "两次密码不一致", null);
        }
        SysUser sysUser1 = new SysUser();
        sysUser1.setPassword(SecureUtil.md5(changePassword.getNewPwd()));
        sysUser1.setId(changePassword.getId());
        this.baseMapper.updateById(sysUser1);
        Map returnMap = new HashMap();
        returnMap.put("userId", changePassword.getId());

        return Result.succ(1, "修改成功", returnMap);
    }

    @Override
    public Result getPersionByDeptId(String deptId, Integer pageSize, Integer pageIndex) {
        Page<SysUser> page = new Page<>();
        Map returnMap = new HashMap();
        List<String> collect = new ArrayList<>();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);
        LambdaQueryWrapper<SysUserDept> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserDept::getDeptId, deptId).eq(SysUserDept::getDelFlag, 0);
        List<SysUserDept> sysUserDepts = sysUserDeptService.getBaseMapper().selectList(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(sysUserDepts)) {
            collect = sysUserDepts.stream().map(SysUserDept::getUserId).collect(Collectors.toList());
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();

        if (CollectionUtils.isNotEmpty(collect)) {
            lambdaQueryWrapper1.in(SysUser::getId, collect).eq(SysUser::getDelFlag, 0);
            Page<SysUser> page1 = sysUserMapper.selectPage(page, lambdaQueryWrapper1);
            returnMap.put("persionList", page1.getRecords());
            returnMap.put("count", page1.getTotal());
        } else {
            returnMap.put("persionList", new ArrayList<>());
            returnMap.put("count", 0);
        }
        return Result.succ(1, "查询成功", returnMap);
    }

    @Override
    public Result getUserInfoList(SysUser user) {
        MPJLambdaWrapper<SysUser> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        if (user.getOrgId() != null && !(user.getOrgId()).equals("")) {
            lambdaQueryWrapper.eq(SysUser::getOrgId, user.getOrgId());
        }
        if (StringUtils.isNotBlank(user.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysUser::getUsername, user.getKeywords()).or().like(SysUser::getRealname, user.getKeywords()));
        }
        if (StrUtil.isNotEmpty(user.getCompanyCode())) {
            StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_INSPECT_COMPANY_USER t2 WHERE t2.DEL_FLAG=0 and t.USERNAME = t2.USERNAME ");
            lambdaQueryWrapper.notExists(existsSql.toString());
        }
        if (StringUtils.isNotBlank(user.getDeptId())) {
            LambdaQueryWrapper<SysUserDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserDept::getDeptId, user.getDeptId()).eq(SysUserDept::getDelFlag, 0);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(queryWrapper);
            List<String> userIds = sysUserDepts.stream().map(SysUserDept::getUserId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SysUser::getId, userIds);
        }
        List<SysUser> sysUsers = sysUserMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", sysUsers);
    }

    @Override
    public Result getTestUserInfoList(SysUser user) {
        MPJLambdaWrapper<SysUser> lambdaQueryWrapper1 = new MPJLambdaWrapper<>();
        lambdaQueryWrapper1.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper1.eq(SysUser::getIsTestDoctor, 1);
        List<SysUser> sysUsers1 = sysUserMapper.selectList(lambdaQueryWrapper1);
        if (CollectionUtils.isNotEmpty(sysUsers1)) {
            return Result.succ(1, "查询成功", sysUsers1);
        }

        MPJLambdaWrapper<SysUser> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        if (user.getOrgId() != null && !(user.getOrgId()).equals("")) {
            lambdaQueryWrapper.eq(SysUser::getOrgId, user.getOrgId());
        }
        if (StringUtils.isNotBlank(user.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysUser::getUsername, user.getKeywords()).or().like(SysUser::getRealname, user.getKeywords()));
        }
        if (StrUtil.isNotEmpty(user.getCompanyCode())) {
            StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_INSPECT_COMPANY_USER t2 WHERE t2.DEL_FLAG=0 and t.USERNAME = t2.USERNAME ");
            lambdaQueryWrapper.notExists(existsSql.toString());
        }
        if (StringUtils.isNotBlank(user.getDeptId())) {
            LambdaQueryWrapper<SysUserDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserDept::getDeptId, user.getDeptId()).eq(SysUserDept::getDelFlag, 0);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(queryWrapper);
            List<String> userIds = sysUserDepts.stream().map(SysUserDept::getUserId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SysUser::getId, userIds);
        }

        List<SysUser> sysUsers = sysUserMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", sysUsers);
    }

    @Override
    public Result getChkUserInfoList(SysUser user) {
        MPJLambdaWrapper<SysUser> lambdaQueryWrapper1 = new MPJLambdaWrapper<>();
        lambdaQueryWrapper1.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper1.eq(SysUser::getIsChkDoctor, 1);
        List<SysUser> sysUsers1 = sysUserMapper.selectList(lambdaQueryWrapper1);
        if (CollectionUtils.isNotEmpty(sysUsers1)) {
            return Result.succ(1, "查询成功", sysUsers1);
        }

        MPJLambdaWrapper<SysUser> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        if (user.getOrgId() != null && !(user.getOrgId()).equals("")) {
            lambdaQueryWrapper.eq(SysUser::getOrgId, user.getOrgId());
        }
        if (StringUtils.isNotBlank(user.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysUser::getUsername, user.getKeywords()).or().like(SysUser::getRealname, user.getKeywords()));
        }
        if (StrUtil.isNotEmpty(user.getCompanyCode())) {
            StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_INSPECT_COMPANY_USER t2 WHERE t2.DEL_FLAG=0 and t.USERNAME = t2.USERNAME ");
            lambdaQueryWrapper.notExists(existsSql.toString());
        }
        if (StringUtils.isNotBlank(user.getDeptId())) {
            LambdaQueryWrapper<SysUserDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserDept::getDeptId, user.getDeptId()).eq(SysUserDept::getDelFlag, 0);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(queryWrapper);
            List<String> userIds = sysUserDepts.stream().map(SysUserDept::getUserId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SysUser::getId, userIds);
        }
        List<SysUser> sysUsers = sysUserMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", sysUsers);
    }

    @Override
    public Result importUserByEmploy(ImportUserAddParam importUserAddParam) {
        // 查询员工列表
        List<PubEmployee> employeeList = pubEmployeeService.findEmployeeListByIds(importUserAddParam.getEmployeeIds());
        // 如果用户表中存在员工code过滤掉
        List<String> collect = employeeList.stream().map(PubEmployee::getCode).collect(Collectors.toList());
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, "0").in(SysUser::getHisEmployeeCode, collect);
        List<SysUser> sysUsers1 = sysUserMapper.selectList(lambdaQueryWrapper);
        List<PubEmployee> collect1 = employeeList.stream().filter(em -> !sysUsers1.stream().map(SysUser::getHisEmployeeCode).collect(Collectors.toList()).contains(em.getCode())).collect(Collectors.toList());
        List<SysUser> sysUsers = importUsers(importUserAddParam.getRoleId(), collect1, "1");
        if (sysUsers.size() > 0) {
            return Result.succ(1, "同步数据成功", sysUsers);
        } else {
            return Result.fail("同步数据失败");
        }
    }

    @Override
    public Result getUserNameAndOrgName(String userName) {
        MPJLambdaWrapper<SysUser> mPJLambdaWrapper = new MPJLambdaWrapper<>();
        mPJLambdaWrapper.selectAll(SysUser.class).selectAs(SysOrganization::getName, SysUser::getOrgName).leftJoin(SysOrganization.class, SysOrganization::getId, SysUser::getOrgId).eq(SysUser::getUsername, userName).eq(SysUser::getDelFlag, 0);

        SysUser sysUser = sysUserMapper.selectOne(mPJLambdaWrapper);
        System.out.println(sysUser);

        return Result.succ(1, "查询成功！", sysUser);
    }

    /**
     * @param roleId
     * @param employees
     * @param savaType  0 表示只插入中间表； 1 表示插入中间表和用户表
     * @return
     */
    @Transactional
    public List<SysUser> importUsers(String roleId, List<PubEmployee> employees, String savaType) {
        List<SysUser> sysUsers = buildBatchUsers(employees);
        if (StringUtils.isNotBlank(roleId) && savaType.equals("1")) {
            this.saveBatch(sysUsers);
            List<SysUserRole> sysUserRoles = buildBatchUserRoles(sysUsers, roleId);
            sysUserRoleService.saveBatch(sysUserRoles);
        } else if (StringUtils.isNotBlank(roleId) && savaType.equals("0")) {
            List<SysUserRole> sysUserRoles = buildBatchUserRoles(sysUsers, roleId);
            sysUserRoleService.saveBatch(sysUserRoles);
        } else {
            this.saveBatch(sysUsers);
        }
        return sysUsers;
    }

    public List<SysUser> buildBatchUsers(List<PubEmployee> employeeList) {
        List<SysUser> users = new ArrayList<>();
        employeeList.forEach(employee -> {
            SysUser sysUser = new SysUser();
            String userName = PinyinUtil.getPinyin(employee.getName(), "");
            sysUser.setUsername(userName);
            sysUser.setPassword(SecureUtil.md5("123456"));
            sysUser.setOrgId(employee.getOrgId());
            sysUser.setDeptId(employee.getDeptId());
            sysUser.setEnable("0");
            sysUser.setRealname(employee.getName());
            sysUser.setDelFlag(0);
            sysUser.setHisEmployeeCode(employee.getCode());
            sysUser.setTel(StringUtils.isNotBlank(employee.getPhone()) ? employee.getPhone() : "");
            users.add(sysUser);
        });
        return users;
    }

    public List<SysUserRole> buildBatchUserRoles(List<SysUser> users, String roleId) {
        List<SysUserRole> userRoles = new ArrayList<>();
        users.forEach(user -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(user.getId());
            sysUserRole.setRoleId(roleId);
            userRoles.add(sysUserRole);
        });
        return userRoles;
    }

    @Override
    public Result checkEmpowerNum(String username, String empowerNum) {
        if (StrUtil.isEmpty(empowerNum) || StrUtil.isEmpty(username)) {
            return Result.fail("用户名或验证码为空！！");
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = this.baseMapper.selectOne(lambdaQueryWrapper);
        boolean check = StrUtil.isNotEmpty(sysUser.getEmpowerNum()) ? empowerNum.equals(sysUser.getEmpowerNum()) : false;
        return Result.succ(1, "查询成功", check);
    }

    @Override
    public Result getSignatureFilePath(String id) {
        if (StringUtils.isBlank(id)) {
            return Result.fail("id为空");
        }
        SysUser user = sysUserMapper.selectById(id);
        File file = new File(user.getSignUrl());
        String fileName1 = file.getName();
        String filename = "/image/" + fileName1;
        return Result.succ(1, "查询成功", filename);
    }

    /**
     * 更新电子签名路径
     *
     * @param id
     * @param signatureUrl
     * @return
     */
    @Override
    public Result uploadSignatureFile(String id, String signatureUrl) {
        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(SysUser::getSignUrl, signatureUrl).eq(SysUser::getId, id);
        int update = sysUserMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "上传电子签名成功", update);
        } else {
            return Result.fail("上传电子签名失败！");
        }
    }


    @Override
    public Result syncUserInfo(OrganizationDTO organizationDTO) {
        //获取索引
        String indexVal = AlphabetArray.Alphabet[organizationDTO.getOrgIndex()];
        //获取来源orgid
        String sourceOrgId = organizationDTO.getSourceOrgId();
        //获取目标orgid
        String goalOrgId = organizationDTO.getGoalOrgId();

        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getOrgId, sourceOrgId).eq(SysUser::getDelFlag,0).eq(SysUser::getUsername,"admin");
        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper);

        if (sysUser == null) {
            return Result.fail("未找到该机构管理员，请先添加管理员！");
        }

        //查询组织机构名称
        LambdaQueryWrapper<SysOrganization> sysOrganizationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysOrganizationLambdaQueryWrapper.eq(SysOrganization::getId, goalOrgId);
        SysOrganization sysOrganization = sysOrganizationMapper.selectOne(sysOrganizationLambdaQueryWrapper);
        String orgName = sysOrganization.getName();

        //转换组织机构名称为拼音码
        String orgNamePinyin = PinyinUtil.getFirstLetter(orgName, "");

        //新的管理员
        String newUserName = orgNamePinyin + "admin";

        LambdaQueryWrapper<SysUser> sysUserQueryWrapper = new LambdaQueryWrapper<>();
        sysUserQueryWrapper.eq(SysUser::getUsername,newUserName).eq(SysUser::getOrgId, goalOrgId).eq(SysUser::getDelFlag,0);
        SysUser newUser = sysUserMapper.selectOne(sysUserQueryWrapper);

        if (newUser != null){
            String userId = newUser.getId();

            sysUserRptGroupMapper.delete(new LambdaQueryWrapper<SysUserRptGroup>().eq(SysUserRptGroup::getUserId, userId).eq(SysUserRptGroup::getOrgId, goalOrgId).eq(SysUserRptGroup::getDelFlag,0));
            sysUserInstrSetupMapper.delete(new LambdaQueryWrapper<SysUserInstrSetup>().eq(SysUserInstrSetup::getUserId, userId).eq(SysUserInstrSetup::getOrgId, goalOrgId).eq(SysUserInstrSetup::getDelFlag,0));
            sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId).eq(SysUserRole::getOrgId, goalOrgId).eq(SysUserRole::getDelFlag,0));
            sysUserDeptMapper.delete(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, userId).eq(SysUserDept::getOrgId, goalOrgId).eq(SysUserDept::getDelFlag,0));
            sysUserAuthdetailMapper.delete(new LambdaQueryWrapper<SysUserAuthdetail>().eq(SysUserAuthdetail::getUserId, userId).eq(SysUserAuthdetail::getOrgId, goalOrgId).eq(SysUserAuthdetail::getDelFlag,0));
            sysUserAuthdifferMapper.delete(new LambdaQueryWrapper<SysUserAuthdiffer>().eq(SysUserAuthdiffer::getUserId, userId).eq(SysUserAuthdiffer::getOrgId, goalOrgId).eq(SysUserAuthdiffer::getDelFlag,0));
            sysUserMapper.deleteById(userId);
        }

        SysUser sysUserNew = new SysUser();
        BeanUtil.copyProperties(sysUser, sysUserNew,"id","username");
        sysUserNew.setUsername(newUserName);
        sysUserNew.setOrgId(goalOrgId);

        sysUserMapper.insert(sysUserNew);

        //复制用户部门
        LambdaQueryWrapper<SysUserDept> sysUserDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserDeptLambdaQueryWrapper.eq(SysUserDept::getUserId, sysUser.getId()).eq(SysUserDept::getOrgId, sourceOrgId).eq(SysUserDept::getDelFlag, 0);
        List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(sysUserDeptLambdaQueryWrapper);

        List<SysUserDept> sysUserDeptList=new ArrayList<>();
        for (SysUserDept sysUserDept : sysUserDepts){
            SysUserDept newSysuserDept=new SysUserDept();
            BeanUtil.copyProperties(sysUserDept,newSysuserDept,"id","userId","orgId","deptId");

            String id = sysUserDept.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserDept.setId(newId);
            newSysuserDept.setUserId(sysUserNew.getId());
            newSysuserDept.setOrgId(goalOrgId);

            String deptId = sysUserDept.getDeptId();
            if (StrUtil.isNotEmpty(deptId)){
                String newDeptId = indexVal + deptId.substring(indexVal.length());
                newSysuserDept.setDeptId(newDeptId);
            }
            sysUserDeptList.add(newSysuserDept);

        }
        sysUserDeptService.saveBatch(sysUserDeptList);

        //复制用户权限
        LambdaQueryWrapper<SysUserAuthdetail> sysUserAuthdetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserAuthdetailLambdaQueryWrapper.eq(SysUserAuthdetail::getUserId, sysUser.getId()).eq(SysUserAuthdetail::getOrgId, sourceOrgId).eq(SysUserAuthdetail::getDelFlag, 0);

        List<SysUserAuthdetail> sysUserAuthdetails = sysUserAuthdetailMapper.selectList(sysUserAuthdetailLambdaQueryWrapper);

        List<SysUserAuthdetail> sysUserAuthdetailList=new ArrayList<>();
        for (SysUserAuthdetail sysUserAuthdetail : sysUserAuthdetails){
            SysUserAuthdetail newSysuserAuthdetail=new SysUserAuthdetail();
            BeanUtil.copyProperties(sysUserAuthdetail,newSysuserAuthdetail,"id","userId","orgId","userName","roleId","moduleId","functionId");

            String id = sysUserAuthdetail.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserAuthdetail.setId(newId);
            newSysuserAuthdetail.setOrgId(goalOrgId);
            newSysuserAuthdetail.setUserId(sysUserNew.getId());
            newSysuserAuthdetail.setUserName(sysUserNew.getUsername());

            String roleId = sysUserAuthdetail.getRoleId();
            if (StrUtil.isNotEmpty(roleId)){
                String newRoleId = indexVal + roleId.substring(indexVal.length());
                newSysuserAuthdetail.setRoleId(newRoleId);
            }
            String moduleId = sysUserAuthdetail.getModuleId();
            if (StrUtil.isNotEmpty(moduleId)){
                String newModuleId = indexVal + moduleId.substring(indexVal.length());
                newSysuserAuthdetail.setModuleId(newModuleId);
            }
            String functionId = sysUserAuthdetail.getFunctionId();
            if (StrUtil.isNotEmpty(functionId)){
                String newFunctionId = indexVal + functionId.substring(indexVal.length());
                newSysuserAuthdetail.setFunctionId(newFunctionId);
            }

            sysUserAuthdetailList.add(newSysuserAuthdetail);

        }
        sysUserAuthdetailService.saveBatch(sysUserAuthdetailList);
        //复制用户权限
        LambdaQueryWrapper<SysUserAuthdiffer> sysUserAuthdifferLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserAuthdifferLambdaQueryWrapper.eq(SysUserAuthdiffer::getOrgId, sourceOrgId).eq(SysUserAuthdiffer::getUserId, sysUser.getId()).eq(SysUserAuthdiffer::getDelFlag, 0);
        List<SysUserAuthdiffer> sysUserAuthdiffers = sysUserAuthdifferMapper.selectList(sysUserAuthdifferLambdaQueryWrapper);

        List<SysUserAuthdiffer> sysUserAuthdifferList=new ArrayList<>();
        for (SysUserAuthdiffer sysUserAuthdiffer : sysUserAuthdiffers){
            SysUserAuthdiffer newSysuserAuthdiffer=new SysUserAuthdiffer();
            BeanUtil.copyProperties(sysUserAuthdiffer,newSysuserAuthdiffer,"id","userId","orgId","userName","roleId","moduleId","functionId");

            String id = sysUserAuthdiffer.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserAuthdiffer.setId(newId);
            newSysuserAuthdiffer.setOrgId(goalOrgId);
            newSysuserAuthdiffer.setUserId(sysUserNew.getId());
            newSysuserAuthdiffer.setUserName(sysUserNew.getUsername());

            String roleId = sysUserAuthdiffer.getRoleId();
            if (StrUtil.isNotEmpty(roleId)){
                String newRoleId = indexVal + roleId.substring(indexVal.length());
                newSysuserAuthdiffer.setRoleId(newRoleId);
            }
            String moduleId = sysUserAuthdiffer.getModuleId();
            if (StrUtil.isNotEmpty(moduleId)){
                String newModuleId = indexVal + moduleId.substring(indexVal.length());
                newSysuserAuthdiffer.setModuleId(newModuleId);
            }
            String functionId = sysUserAuthdiffer.getFunctionId();
            if (StrUtil.isNotEmpty(functionId)){
                String newFunctionId = indexVal + functionId.substring(indexVal.length());
                newSysuserAuthdiffer.setFunctionId(newFunctionId);
            }
            sysUserAuthdifferList.add(newSysuserAuthdiffer);
        }
        sysUserAuthdifferService.saveBatch(sysUserAuthdifferList);

        //复制用户检验项目
        LambdaQueryWrapper<SysUserInstrSetup> sysUserInstrSetupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserInstrSetupLambdaQueryWrapper.eq(SysUserInstrSetup::getUserId, sysUser.getId()).eq(SysUserInstrSetup::getOrgId, sourceOrgId).eq(SysUserInstrSetup::getDelFlag, 0);
        List<SysUserInstrSetup> sysUserInstrSetups = sysUserInstrSetupMapper.selectList(sysUserInstrSetupLambdaQueryWrapper);
        List<SysUserInstrSetup> sysUserInstrSetupList=new ArrayList<>();
        for (SysUserInstrSetup sysUserInstrSetup : sysUserInstrSetups){
            SysUserInstrSetup newSysuserInstrSetup=new SysUserInstrSetup();
            BeanUtil.copyProperties(sysUserInstrSetup,newSysuserInstrSetup,"id","userId","orgId","instrSetupId");

            String id = sysUserInstrSetup.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserInstrSetup.setId(newId);
            newSysuserInstrSetup.setUserId(sysUserNew.getId());
            newSysuserInstrSetup.setOrgId(goalOrgId);

            String instrSetupId = sysUserInstrSetup.getInstrSetupId();
            if (StrUtil.isNotEmpty(instrSetupId)){
                String newInstrSetupId = indexVal + instrSetupId.substring(indexVal.length());
                newSysuserInstrSetup.setInstrSetupId(newInstrSetupId);
            }

            sysUserInstrSetupList.add(newSysuserInstrSetup);
        }
        SysUserInstrSetupService.saveBatch(sysUserInstrSetupList);

        //复制用户角色
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId, sysUser.getId()).eq(SysUserRole::getOrgId, sourceOrgId).eq(SysUserRole::getDelFlag, 0);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleLambdaQueryWrapper);

        List<SysUserRole> sysUserRoleList=new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoles){
            SysUserRole newSysuserRole=new SysUserRole();
            BeanUtil.copyProperties(sysUserRole,newSysuserRole,"id","userId","orgId","roleId");

            String id = sysUserRole.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserRole.setId(newId);
            newSysuserRole.setUserId(sysUserNew.getId());
            newSysuserRole.setOrgId(goalOrgId);

            String roleId = sysUserRole.getRoleId();
            if (StrUtil.isNotEmpty(roleId)){
                String newRoleId = indexVal + roleId.substring(indexVal.length());
                newSysuserRole.setRoleId(newRoleId);
            }

            sysUserRoleList.add(newSysuserRole);
        }
        sysUserRoleService.saveBatch(sysUserRoleList);

        //复制用户报表分组
        LambdaQueryWrapper<SysUserRptGroup> sysUserRptGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();

        sysUserRptGroupLambdaQueryWrapper.eq(SysUserRptGroup::getUserId, sysUser.getId()).eq(SysUserRptGroup::getOrgId, sourceOrgId).eq(SysUserRptGroup::getDelFlag, 0);

        List<SysUserRptGroup> sysUserRptGroups = sysUserRptGroupMapper.selectList(sysUserRptGroupLambdaQueryWrapper);
        List<SysUserRptGroup> sysUserRptGroupList=new ArrayList<>();
        for (SysUserRptGroup sysUserRptGroup : sysUserRptGroups){
            SysUserRptGroup newSysuserRptGroup=new SysUserRptGroup();
            BeanUtil.copyProperties(sysUserRptGroup,newSysuserRptGroup,"id","userId","orgId","rptGroupId");
            String id = sysUserRptGroup.getId();
            String newId = indexVal + id.substring(indexVal.length());
            newSysuserRptGroup.setId(newId);
            newSysuserRptGroup.setUserId(sysUserNew.getId());
            newSysuserRptGroup.setOrgId(goalOrgId);
            String rptGroupId = sysUserRptGroup.getRptGroupId();
            if (StrUtil.isNotEmpty(rptGroupId)){
                String newRptGroupId = indexVal + rptGroupId.substring(indexVal.length());
                newSysuserRptGroup.setRptGroupId(newRptGroupId);
            }
            sysUserRptGroupList.add(newSysuserRptGroup);
        }

        sysUserRptGroupService.saveBatch(sysUserRptGroupList);

        return Result.succ(1, "同步成功", null);

    }
}
